import os
import glob
import re
import json
from PIL import Image

def process_images(input_dir, output_dir=None, operations=None, crop_box=None, rename_prefix="image", rename_start_num=1):
    """
    批量处理图片（裁剪和/或重命名）
    
    参数:
        input_dir: 输入图片目录
        output_dir: 输出目录（None表示原地处理）
        operations: 要执行的操作列表，如['crop', 'rename']
        crop_box: 裁剪区域(left, top, right, bottom)
        rename_prefix: 重命名前缀
        rename_start_num: 重命名起始编号
    """
    if not operations:
        print("请指定要执行的操作（operations参数）")
        return
    output_dir = input_dir + "_" + output_dir
    # 确保输出目录存在
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 获取图片文件列表
    image_files = glob.glob(os.path.join(input_dir, '*.[jJ][pP][gG]')) + \
                 glob.glob(os.path.join(input_dir, '*.[jJ][pP][eE][gG]'))
    image_files.sort(key=lambda x: [int(c) if c.isdigit() else c for c in re.split('([0-9]+)', x)])
    
    if not image_files:
        print(f"在目录 {input_dir} 中未找到JPG/JPEG图片")
        return
    
    print(f"找到 {len(image_files)} 张图片:")
    for i, filepath in enumerate(image_files, start=1):
        print(f"{i}. {os.path.basename(filepath)}")
    
    confirm = input("\n确认要处理这些文件吗？(y/n): ").strip().lower()
    if confirm != 'y':
        print("操作已取消")
        return
    
    # 初始化变量
    counter = rename_start_num
    processed_files = []
    json_dict = {"title": input_dir, "catalogue": []}
    
    for old_path in image_files:
        filename = os.path.basename(old_path)
        try:
            with Image.open(old_path) as img:
                img_width, img_height = img.size
                
                # 确定输出文件名
                if 'rename' in operations:
                    ext = os.path.splitext(filename)[1].lower()
                    new_name = f"{rename_prefix}_{counter:04d}{ext}"
                    json_dict["catalogue"].append(new_name)
                    counter += 1
                else:
                    new_name = filename
                
                # 确定输出路径
                if output_dir:
                    final_path = os.path.join(output_dir, new_name)
                else:
                    final_path = os.path.join(os.path.dirname(old_path), new_name)
                
                # 执行裁剪操作
                if 'crop' in operations and crop_box:
                    left, top, right, bottom = crop_box
                    left = max(0, left)
                    top = max(0, top)
                    right = min(img_width, right)
                    bottom = min(img_height, bottom)
                    
                    cropped_img = img.crop((left, top, right, bottom))
                    cropped_img.save(final_path)
                    print(f"成功裁剪并保存: {filename} -> {new_name}")
                else:
                    # 如果没有裁剪操作，直接保存（重命名）
                    img.save(final_path)
                    print(f"成功保存: {filename} -> {new_name}")
                
                processed_files.append((filename, new_name))
                
        except Exception as e:
            print(f"处理 {filename} 时出错: {e}")
    
    # 保存重命名信息到JSON
    if 'rename' in operations:
        json_path = os.path.join(output_dir, 'information.json')
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(json_dict, f, ensure_ascii=False, indent=4)
        print(f"\n重命名信息已保存到 {json_path}")
    
    print("\n处理完成:")
    for old, new in processed_files:
        print(f"{old} -> {new}")

# 使用示例:
# process_images('input_images', 'output', operations=['crop', 'rename'], crop_box=(100, 100, 500, 500))
# process_images('input_images', operations=['rename'], rename_prefix="pic", rename_start_num=1)
#只裁剪：process_images('input', 'output', operations=['crop'], crop_box=(x1,y1,x2,y2))
#只重命名：process_images('input', operations=['rename'])
#裁剪并重命名：process_images('input', 'output', operations=['crop','rename'], crop_box=(x1,y1,x2,y2))

if __name__ == "__main__":
    process_images('人工智能训练师（基础知识）', 'output', operations=['crop','rename'], crop_box=(260, 400, 2480, 3505))